package org.budo.support.spring.format.support;

import java.time.LocalDateTime;

import org.budo.time.Time;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.format.support.DefaultFormattingConversionService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class BudoFormattingConversionService extends DefaultFormattingConversionService {
    @Override
    public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return super.canConvert(sourceType, targetType);
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        try {
            if ("java.time.LocalDateTime".equals(targetType.toString())) {
                LocalDateTime localDateTime = Time.when(source).toLocalDateTime();
                return localDateTime;
            }

            return super.convert(source, sourceType, targetType);
        } catch (Throwable e) {
            log.error("#31 convert error, source=" + source + ", sourceType=" + sourceType + ", targetType=" + targetType + ", e=" + e, e);
            return null;
        }
    }

    @Override
    public boolean canConvert(Class<?> sourceType, Class<?> targetType) {
        return super.canConvert(sourceType, targetType);
    }

    @Override
    public <T> T convert(Object source, Class<T> targetType) {
        return super.convert(source, targetType);
    }

    @Override
    public Object convert(Object source, TypeDescriptor targetType) {
        return super.convert(source, targetType);
    }
}